package com.dftdla.server.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dftdla.dao.pojo.ChatGroup;
import com.dftdla.dao.pojo.UserGroup;
import com.dftdla.dao.service.ChatGroupService;
import com.dftdla.dao.service.UserGroupService;
import com.dftdla.result.ResponseResult;
import com.dftdla.server.message.request.GroupJoinRequestMessage;
import com.dftdla.server.session.Session;
import com.dftdla.util.Code;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 14501
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {

    @Resource
    private UserGroupService userGroupService;
    @Resource
    private ChatGroupService chatGroupService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        Long userId = msg.getUserId();
        Long groupId = msg.getGroupId();

        ChatGroup group = chatGroupService.getById(groupId);
        String result;

        if(group == null){
            result = new ResponseResult<>(Code.BAD_REQUEST.code,"不存在的群组").toString();
        }else{
            LambdaQueryWrapper<UserGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserGroup::getGroupId,groupId)
                    .eq(UserGroup::getUser,userId);
            UserGroup one = userGroupService.getOne(wrapper);
            if(one != null){
                result = new ResponseResult<>(Code.BAD_REQUEST.code, "用户已在群组中").toString();
            }else{
                UserGroup userGroup = new UserGroup();
                userGroup.setUser(userId);
                userGroup.setGroupId(groupId);
                userGroupService.save(userGroup);
                result = new ResponseResult<>(Code.SUCCESS).toString();
            }
        }
        ctx.writeAndFlush(new TextWebSocketFrame(result));
    }
}
